<template>
  <div>
    <div class="container">
      <!-- 添加按钮-->
      <el-button style="float: left;" type="primary" icon="el-icon-circle-plus-outline" class="handle-del mr10"
        @click="addDialogFormVisible">添加广告</el-button>
      <el-form :inline="true" :model="editForm" class="user-search" style="float: right;">
        <!-- 下拉框状态-->
        <el-select v-model="editForm.codeName" placeholder="广告状态" class="handle-select mr10">
          <el-option key="1" label="活动中" value="7"></el-option>
          <el-option key="2" label="已结束" value="8"></el-option>
        </el-select>
        <!-- 搜索框-->
        <el-input v-model="editForm.name" placeholder="广告标题" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <!-- </div> -->
      </el-form>
      <!-- 表格数据 -->
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column header-align="center" align="center" type="index" label="序号" fixed="left"></el-table-column>
        <el-table-column prop="advertiseId" label="ID" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="广告标题" align="center"></el-table-column>
        <el-table-column prop="image" label="宣传图(查看大图)" align="center">
          <template #default="scope">
            <el-image class="table-td-thumb" :src="ip+scope.row.image" :preview-src-list="[ip+scope.row.image]">
            </el-image>
          </template>
        </el-table-column>
        <!-- 状态-->
        <el-table-column prop="codeName" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="
				                scope.row.codeName === '活动中'
				                    ? 'success'
				                    : scope.row.codeName === '已结束'
				                    ? 'danger'
				                    : ''
				            ">{{ scope.row.codeName }}</el-tag>
          </template>
        </el-table-column>
        <!-- 操作按钮-->
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.state==8" type="text" icon="el-icon-caret-top"
              @click="start(scope.$index, scope.row)">开始</el-button>
            <el-button v-if="scope.row.state==7" type="text" icon="el-icon-caret-bottom" class="red"
              @click="end(scope.$index, scope.row)">结束
            </el-button>
            <el-button type="text" icon="el-icon-edit" @click="openEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页-->
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="this.pageIndex"
          :page-size="this.pageSize" :total="pageTotal" @size-change="handleSizeChange"
          @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="updform" label-width="70px">
        <el-form-item label="广告标题">
          <el-input v-model="updform.name"></el-input>
        </el-form-item>
        <el-form-item label="图片上传">
          <el-upload v-model="updform.image" class="upload-demo"
            action="http://43.142.173.112:9090/adminAdvertise/uploadImage" :on-success="onSuccess"
            :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture">
            <el-button size="small" type="primary">点击上传商品图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="宣传图">
          <el-image class="table-td-thumb" :src="ip+updform.image" :preview-src-list="[ip+updform.image]">
          </el-image>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加弹出框 -->
    <el-dialog title="添加" :visible.sync="editVisible1" width="30%">
      <el-form ref="form" :model="addform" label-width="70px">
        <el-form-item label="广告标题">
          <el-input v-model="addform.name"></el-input>
        </el-form-item>
        <el-form-item label="分店编号">
          <!-- <el-select v-model="addform.shopsId" placeholder="分店编号" class="handle-select mr10">
            <el-option key="1" label="1" value="1"></el-option>
            <el-option key="2" label="2" value="2"></el-option>
            <el-option key="3" label="3" value="3"></el-option>
            <el-option key="4" label="4" value="4"></el-option>
            <el-option key="5" label="5" value="5"></el-option>
            <el-option key="6" label="6" value="6"></el-option>
          </el-select> -->
          <el-input v-model="addform.shopsId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="宣传图">
          <el-upload v-model="addform.image" class="upload-demo"
            action="http://43.142.173.112:9090/adminAdvertise/uploadImage" :on-success="onSuccess"
            :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture">
            <el-button size="small" type="primary">点击上传商品图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exit">取 消</el-button>
        <el-button type="primary" @click="saveEdit1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    mounted() {
      this.handleSearch()
    },
    data() {
      return {
        fileList: [{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }],
        editForm: {
          name: "",
          codeName: ""
        },
        pageIndex: 1,
        pageSize: 5,
        pageTotal: 0,
        tableData: [],
        form: {
          codeName: "",
          name: "",
          image: "",
          advertiseId: ""
        },
        addform: {
          name: "",
          image: "",
          shopsId: ""
        },
        updform: {
          name: "",
          image: "",
          advertiseId: ""
        },
        multipleSelection: [],
        delList: [],
        editVisible: false,
        editVisible1: false,
        ip:'http://43.142.173.112:16622/images/',
        idx: -1,
        id: -1
      };
    },
    methods: {
      handleRemove(file, fileList) {},
      handlePreview(file) {
        console.log("上传图片", file);
      },
      onSuccess(response) {
        this.$data.updform.image = response.fileUrl,
          this.$data.addform.image = response.fileUrl
        console.log("图片路径", response.fileUrl)
      },
      onSubmit() {
        console.log(this.fileList)
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      // 触发搜索按钮
      handleSearch() {
        console.log(this.editForm.codeName)
        let state
        if (this.editForm.codeName == "" || this.editForm.codeName == null) {
          state = 0
        } else {
          state = this.editForm.codeName
        }
        console.log(state)
        var userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
        this.$axios.post('/adminAdvertise/advertiseList', this.$qs.stringify({
          pagenum: this.$data.pageIndex,
          pagesize: this.$data.pageSize,
          state: state,
          name: this.editForm.name,
          shopsId: userInfo.shopsId,
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
        })).then(response => {
          console.log(response)
          if (response.data != null) {
            console.log(response.data)
            // 接收后台发来的map集合table是表数据，total是总数
            this.tableData = response.data.table
            console.log("图片回显：", this.tableData)
            this.pageTotal = response.data.total
          }
        }).catch(err => {
          alert(err)
        })
      },
      // 删除操作
      handleDelete(index, row) {
        this.$confirm('此操作将删除广告, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post('/adminAdvertise/delAdvertise', this.$qs.stringify({
            advertiseId: row.advertiseId
          })).then(response => {
            console.log(response)
            if (response.data != null) {
              console.log('数据接收');
              console.log(response.data)
              if (response.data == '1') {
                this.$message({
                  type: 'success',
                  message: '广告已删除!'
                });
                this.handleSearch();
              } else {
                this.$message({
                  type: 'fail',
                  message: '广告删除失败!'
                });
              }
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消广告删除'
          });
        });
      },
      // 开始操作
      start(index, row) {
        this.$confirm('此操作将开始活动, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post('/adminAdvertise/startAdvertise', this.$qs.stringify({
            advertiseId: row.advertiseId
          })).then(response => {
            console.log(response)
            if (response.data != null) {
              console.log('数据接收');
              console.log(response.data)
              if (response.data == '1') {
                this.$message({
                  type: 'success',
                  message: '活动已开启!'
                });
                this.handleSearch();
              } else {
                this.$message({
                  type: 'fail',
                  message: '活动开启失败!'
                });
              }
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消开始活动'
          });
        });
      },
      // 结束操作
      end(index, row) {
        this.$confirm('此操作将结束活动, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post('/adminAdvertise/stopAdvertise', this.$qs.stringify({
            advertiseId: row.advertiseId
          })).then(response => {
            console.log(response)
            if (response.data != null) {
              console.log('数据接收');
              console.log(response.data)
              if (response.data == '1') {
                this.$message({
                  type: 'success',
                  message: '活动已结束!'
                });
                this.handleSearch();
              } else {
                this.$message({
                  type: 'fail',
                  message: '活动结束失败!'
                });
              }
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消结束活动'
          });
        });
      },
      // 多选操作
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      delAllSelection() {
        const length = this.multipleSelection.length;
        let str = '';
        this.delList = this.delList.concat(this.multipleSelection);
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].name + ' ';
        }
        this.$message.error(`删除了${str}`);
        this.multipleSelection = [];
      },
      // 编辑操作
      openEdit(index, row) {
        this.updform.advertiseId = row.advertiseId;
        this.updform.name = row.name;
        this.updform.image = row.image;
        this.editVisible = true;
      },
      // 编辑
      saveEdit() {
        this.$axios.post(
            '/adminAdvertise/updAdvertise', this.$qs.stringify({
              name: this.$data.updform.name,
              advertiseId: this.$data.updform.advertiseId,
              image: this.$data.updform.image
            }))
          .then(response => {
            if (response.data != null) {
              console.log(response.data)
              if (response.data == '1') {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                });
                this.$data.addVisible = false;
                window.location.reload() // 强制刷新
                this.handleSearch();
              } else {
                this.$message({
                  type: 'fail',
                  message: '修改失败!'
                });
              }
            }
          })
        this.editVisible = false;
        this.tableData[this.idx].name = this.form.name;
      },
      // 添加操作
      addDialogFormVisible() {
        this.editVisible1 = true;
        var userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
        this.addform.name = "";
        this.addform.image = "";
        this.addform.shopsId=userInfo.shopsId
      },
      // 添加界面添加按钮
      saveEdit1: function() {
        this.$axios.post(
            '/adminAdvertise/addAdvertise', this.$qs.stringify({
              name: this.$data.addform.name,
              image: this.$data.addform.image,
              shopsId: this.$data.addform.shopsId,
            }))
          .then(response => {
            if (response.data != null) {
              console.log(response.data)
              if (response.data == '1') {
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                });
                this.$data.addVisible1 = false;
                window.location.reload() // 强制刷新
                this.handleSearch();
              } else {
                this.$message({
                  type: 'fail',
                  message: '添加失败!'
                });
              }
            }
          })
        this.editVisible1 = false;
        this.updform.image = "";
        this.tableData[this.idx].name = this.form.name
      },

      // 添加界面取消按钮
      exit() {
        this.$data.editVisible1 = false;
        this.$data.form.name = '';
        this.$data.form.shopsId = '';
        this.$data.form.image = '';
      },
      // 分页导航
      handlePageChange(val) {
        this.pageIndex = val
        this.handleSearch();
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.handleSearch();
      },
    }
  };
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .mr10 {
    margin-right: 10px;
  }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
</style>
